const { callModel } = require("../model");

//创建公告
exports.createNotice = async (req, res) => {
  const { title, content } = req.body;
  if (title == undefined || content == undefined) {
    return res.status(400).json({
      code: 400,
      message: "请填写完整信息",
      data: null,
    });
  }
  let docId = req?.user?._id;
  try {
    let dbBack = new callModel({
      title,
      content,
      docId,
    });
    await dbBack.save();
    res.status(200).json({
      code: 200,
      message: "创建成功",
      data: null,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "创建失败",
      data: null,
    });
  }
};
//获取公告列表
exports.getCallList = async (req, res) => {
  const { pageNo = 1, pageSize = 20 } = req.query;
  try {
    let result = await callModel
      .find({})
      .skip((pageNo - 1) * pageSize)
      .limit(pageSize)
      .populate("docId", "name TweDepart")
      .sort({ createAt: -1 });
    let total = await (await callModel.find({})).length;
    res.status(200).json({
      code: 200,
      message: "获取成功",
      data: result,
      total,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取失败",
      data: error,
    });
  }
};
//获取公告详情
exports.getCallDetail = async (req, res) => {
  const { id } = req.query;
  if (id == undefined) {
    return res.status(400).json({
      code: 400,
      message: "请输入id",
      data: null,
    });
  }
  try {
    let result = await callModel
      .findById({ _id: id })
      .populate("docId", "name TweDepart");
    res.status(200).json({
      code: 200,
      message: "获取成功",
      data: result,
    });
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "获取失败",
      data: error,
    });
  }
};
//修改公告
exports.updateCall = async (req, res) => {
  const { id } = req.query;
  const { title, content } = req.body;
  if (id == undefined) {
    return res.status(400).json({
      code: 400,
      message: "请输入id",
      data: null,
    });
  }
  try {
    await callModel.findByIdAndUpdate({ _id: id }, { title, content });
    res.status(200).json({
      code: 200,
      message: "修改成功",
      data: null,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "修改失败",
      data: error
    })
  }
};
//删除公告
exports.deleteCall = async (req, res) => {
  const { id } = req.query;
  if (id == undefined) {
    return res.status(400).json({
      code: 400,
      message: "请输入id",
      data: null,
      
    });
    
  }
  try {
    await callModel.findByIdAndDelete({ _id: id });
    res.status(200).json({
      code: 200,
      message: "删除成功",
      data: null,
    })
  } catch (error) {
    res.status(500).json({
      code: 500,
      message: "删除失败",
      data: error
    })
  }
}
